package AI;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Formula {
	  Set<Literal> literalSet = new HashSet<Literal>();
	  Literal resultLiteral;
	  
	  public Formula() {
		  literalSet = new HashSet<Literal>();
		  resultLiteral = null;
	  }
	  
	  public Formula(Set<Literal> sl) {
		  literalSet.addAll(sl);
		  resultLiteral = null;
	  }
	  
	  public Formula(Set<Literal> sl, Literal l) {
		  literalSet.addAll(sl);
		  resultLiteral = l;
	  }
	  
	  public Formula(Formula f) {
		  literalSet = f.getLiteralSet();
		  resultLiteral = f.getLiteral();
	  }
	  
	  public Iterator<Literal> returnIterator() {
		  return literalSet.iterator();
	  }
	  
	  public void setLiteral(Literal l, int place) {
		  if (place == 0) {
			  literalSet.add(l);
		  } else {
			  resultLiteral = l;
		  }
	  }
	  
	  public Set<Literal> getLiteralSet() {
		  return literalSet;
	  }
	  public Literal getLiteral() {
		  return resultLiteral;
	  }
	  
	  public boolean removeLiteral(Literal l, int position) {
		  if (position == 0) {
			  if (getLiteralSet().contains(l)) {
				  getLiteralSet().remove(l);
				  return true;
			  } else {
				  return false;
			  }
		  } else
			  if (getLiteral().equals(l)) {
				  resultLiteral = null;
				  return true;
			  } else {
				  return false;
			  }
	  }
	  
	  public void clearFormula() {
		  literalSet.clear();
		  if (resultLiteral!=null) {
			  resultLiteral = null;
		  }
	  }
	  
	  public boolean isEmpty() {
		  return literalSet.isEmpty();
	  }
	  
	  public boolean equals(Formula f) {
		  if((getLiteralSet().containsAll(f.getLiteralSet()) && getLiteral().equals(f.getLiteral()))
				  || (getLiteralSet().containsAll(f.getLiteralSet()) 
						  && getLiteral()==null && f.getLiteral()==null))
			  return true;
		  else
			  return false;
	  }

	public void print() {
		Iterator<Literal> i = returnIterator();
		while (i.hasNext()) {
			i.next().print();
			System.out.print(" ");
		}
		if (getLiteral() != null) {
			System.out.print("=> ");
			getLiteral().print();			
		}
		System.out.print("\n");
		//s = s.substring(0, s.length()-3);
		/*s.concat(" => ");
		s.concat(getLiteral().toString());
		System.out.println(s);*/
	}
}
